﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LoA.Shared.Interfaces;
using LoA.Shared.Screen;
using Microsoft.Xna.Framework;

namespace LoA {
	public static class GameLoader {
		private static GameComponentCollection gamePlayComponents;
		private static int updateOrder;
		private static int drawOrder;

		private static GameState state;

		static GameLoader( ) {
			gamePlayComponents = new GameComponentCollection( );
			updateOrder = 0;
			drawOrder = 0;
		}
		public static void AddGameComponent(IGameComponent gameComponent) {
			gamePlayComponents.Add(gameComponent);
			if (gameComponent is GameComponent)
				(gameComponent as GameComponent).UpdateOrder = updateOrder++;
			if (gameComponent is DrawableGameComponent)
				(gameComponent as DrawableGameComponent).DrawOrder = drawOrder++;
		}
		public static void LoadTo(GameComponentCollection gameComponentCollection) {
			if (state != (GameState.Loading | GameState.Resuming)) {
				state = GameState.Loading | GameState.Resuming;
				foreach (IGameComponent gameComponent in gamePlayComponents) {
					if (gameComponentCollection.IndexOf(gameComponent) == -1)
						gameComponentCollection.Add(gameComponent);
				}
				state = GameState.Playing;
			}
		}
		public static void UnloadFrom(GameComponentCollection gameComponentCollection) {
			if (state != GameState.Closeing) {
				state = GameState.Closeing;
				foreach (IGameComponent gameComponent in gamePlayComponents) {
					if (gameComponentCollection.IndexOf(gameComponent) > -1)
						gameComponentCollection.Remove(gameComponent);
				}
				state = GameState.NotStarted;
			}
		}
		public static void Dispose( ) {
			gamePlayComponents.Clear( );
		}

		public static void Initialize( ) {
			if (state != GameState.Loading) {
				state = GameState.Loading;
				foreach (IGameComponent gameComponent in gamePlayComponents) {
					gameComponent.Initialize( );
				}
				int i = 0;
				while (i < 1000000)
					i++;
				state = GameState.Playing;
			}
		}

		internal static void Suspend( ) {
			if (state != GameState.Suspending) {
				state = GameState.Suspending;
				foreach (IGameComponent gameComponent in gamePlayComponents) {
					if (gameComponent is ISuspendableGameComponent)
						(gameComponent as ISuspendableGameComponent).Suspend( );
				}
				int i = 0;
				while (i < 1000000) {
					double p = 100.0 / i;
					i++;
				}
				state = GameState.Suspended;
			}
		}

		internal static void Resume( ) {
			if (state != GameState.Resuming) {
				state = GameState.Resuming;
				foreach (IGameComponent gameComponent in gamePlayComponents) {
					if (gameComponent is ISuspendableGameComponent)
						(gameComponent as ISuspendableGameComponent).Resume( );
				}
				int i = 0;
				while (i < 1000000)
					i++;
				state = GameState.Playing;
			}
		}
	}
}
